package com.alcatel_lucent.osp.service;

import com.alcatel_lucent.osp.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Service("authenticationService")
public class AuthenticationServiceImpl extends BaseServiceImpl implements AuthenticationService {

    private static Logger log = LoggerFactory.getLogger(AuthenticationServiceImpl.class);

    @Autowired
    private LDAPService ldapService;

    @Override
    public User login(String username, String password) {
        if (ldapService.login(username, password)
//                || ldapService.login("allany", password)
//                || ldapService.login("guoshunw", password)
                ) {    // login successfully
            log.info("User " + username + " logged in.");
            User user = findUser(username);
            if (user == null) {    // create a new user entry
                user = ldapService.findUserByCSLOrCIL(username);
                if (user == null) {
                    return null;
                }
                user.setCreateTime(new Timestamp(System.currentTimeMillis()));
                user.setActive(true);
                user = (User) dao.create(user);
                log.info("Created new user " + user.getCil() + "(" + user.getCsl() + ")");
            } else if (!user.isActive()) {
                return null;
            }
            user.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
            return user;
        } else {
            return null;
        }
    }


    private User findUser(String CSLOrCIL) {
        String hql = "from User where csl=:name or cil=:name";
        Map param = new HashMap();
        param.put("name", CSLOrCIL);
        return (User) dao.retrieveOne(hql, param, new String[]{"categories"});
    }

}
